<template>
	<view class="content">
		<view class='lang_bar'>
			<view class='lang_itm'>
				<picker @change="bindPickerChange" :value="speekIndex" range-key='label' :range="speekLangs">
					<text class="c-p-r-10">{{speekLangs[speekIndex].label}}</text>
					<text class="icf">&#xe61a;</text>
				</picker>
			</view>
			<text class="icf" style="font-size: 48rpx;">&#xe726;</text>
			<view class='lang_itm'>
				<picker :value="targetIndex" @change="bindTargetChange" :range="targetLangs">
					<text class="c-p-r-10">{{ targetLangs[targetIndex] }}</text>
					<text class="icf">&#xe61a;</text>
				</picker>
			</view>
		</view>
		<scroll-view class="chat-container" scroll-y :scroll-into-view="scrollIntoView">
			<view class="message" :class="{ flexLfet: !msg.isUser }" v-for="(msg, index) in messages" :key="index"
				:id="'msg-' + index">
				<image v-if="msg.isUser" class="avatar" src="/static/img/chat/avatar.png" />
				<image v-else class="avatar" src="/static/img/chat/avatar.png" />
				<view>
					<view class="message-time">{{ msg.time }}</view>
					<view class="message-text c-font-md" :class="{ 'user-message': msg.isUser, 'bot-message': !msg.isUser }">
						<view class="c-text-primary c-p-b-10" v-if='msg.isVoice'>语音识别</view>
						<view class="c-font-md">{{ msg.text }}</view>
						<view class="c-border-top c-m-t-10">
							<view class="c-text-primary c-p-y-10">AI翻译</view>
							<rmLoading v-if='!msg.trans'></rmLoading>
							<view class="c-font-md" v-else>{{ msg.trans }}</view>
						</view>
						<view class="c-border-top c-m-t-10 c-p-t-10 c-text-primary" v-if='msg.voiceUrl'>
							<text class="icf">&#xe662;</text>
							<text class="c-p-l-4" @click="()=>playVoice(msg.voiceUrl)">点击播放</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="input-area">
			<rm-record :voiceRate='voiceRate' v-if='recording' ></rm-record>
			<textarea class="voice-text" v-model="voiceText" :cursor-spacing='10' v-if="recording||voiceText" />
			<view class="text-area">
				<image class="voice-icon" src="/static/img/chat/voice.png" v-if="isVoice" mode="scaleToFill"
					@click="toggleInputMode" />
				<image class="voice-icon" src="/static/img/chat/keyboard.png" v-else mode="scaleToFill"
					@click="toggleInputMode" />
				<view class="input-box voice-btn" v-if="isVoice" @touchstart="startRecognize" @touchend="endRecognize">
					{{recording?'松开结束':'按住说话'}}
				</view>
				<input v-model="newMessage" :cursor-spacing='10' v-else class="input-box" placeholder="输入消息..." />
				<image class="voice-icon" src="/static/img/chat/send.png" mode="scaleToFill" @click="sendMessage" />
			</view>
		</view>
	</view>
</template>

<script>
	import rmLoading from '@/components/rm-loading/rm-loading.vue'
	import rmRecord from '@/components/rm-record/rm-record.vue'
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	innerAudioContext.onPlay(() => {
	  console.log('开始播放');
	});
	innerAudioContext.onError((res)=>{
		console.log('错误',res);
	})
	export default {
		data() {
			return {
				title: 'Hello',
				messages: [],
				newMessage: '',
				isVoice: false,
				scrollIntoView: '',
				voiceText: '',
				recording: false,
				text: '',
				partialResult: '...',
				result: '',
				valueWidth: '0px',
				speekLangs: [{
					label: "中文",
					value:'zh-cn'
				},{
					label: "英文",
					value:'en-us'
				},{
					label: "粤语",
					value:'zh-cantonese'
				}],
				targetLangs: ['英文','中文'],
				speekIndex: 0,
				targetIndex: 0,
				voiceRate: 0 
			}
		},
		components: {rmLoading,rmRecord},
		onLoad() {
			// #ifdef APP-PLUS
			// 监听语音识别事件
			plus.speech.addEventListener('start', this.ontStart, false);
			plus.speech.addEventListener('volumeChange', this.onVolumeChange, false);
			plus.speech.addEventListener('recognizing', this.onRecognizing, false);
			plus.speech.addEventListener('recognition', this.onRecognition, false);
			plus.speech.addEventListener('end', this.onEnd, false);
			// #endif
		},
		onUnload() {
			innerAudioContext.destroy()
			innerAudioContext = null
		},
		methods: {
			bindPickerChange(e){
				this.speekIndex = e.detail.value
			},
			bindTargetChange(e){
				console.log(e)
				this.targetIndex = e.detail.value
			},
			getCurrentTime() {
				const now = new Date();
				return `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
			},
			scrollToBottom() {
				this.scrollIntoView = 'msg-' + (this.messages.length - 1);
			},
			sendMessage() {
				let text = this.isVoice ? this.voiceText.trim() : this.newMessage.trim()
				if (this.newMessage.trim() !== '' && !this.isVoice) {
					this.messages.push({
						text: this.newMessage,
						isUser: true,
						isVoice: this.isVoice,
						time: this.getCurrentTime()
					});
					this.newMessage = '';
					// this.replyFromBot();
					this.$nextTick(() => {
						this.scrollToBottom();
					});
				}
				if (this.voiceText.trim() !== '' && this.isVoice) {
					this.messages.push({
						text: this.voiceText,
						isUser: true,
						isVoice: this.isVoice,
						time: this.getCurrentTime()
					});
					this.voiceText = '';
					// this.replyFromBot();
					this.$nextTick(() => {
						this.scrollToBottom();
					});
				}
				this.getTranslateVoice(text,this.messages.length-1)
			},
			getTranslateVoice(text,index){
				if(!text) return
				let lang = this.targetLangs[this.targetIndex]
				console.log('==========',lang)
				let that = this
				uni.request({
					url: 'https://api.dify.ai/v1/chat-messages',
					method: 'POST',
					header: {
						Authorization: 'Bearer app-sL0ChegYlK2ogxN8FmGjDUD9'
					},
					data: {
						query: text,
						user: "abc-123",
						inputs: { lang },
					},
					success(res) {
						console.log(res)
						let a = res.data.answer
						let b = a.substring(a.indexOf('(') + 1, a.indexOf(')'))
						let c = a.substring(0, a.indexOf('['))
						that.messages[index].trans = c
						that.messages[index].voiceUrl = b
						console.log(that.messages)
					},
					fail(res) {
						console.log("失败=====",res)
					}
				
				})
			},
			replyFromBot() {
				setTimeout(() => {
					this.messages.push({
						text: '这是一个自动回复。',
						isUser: false,
						time: this.getCurrentTime()
					});
					this.$nextTick(() => {
						this.scrollToBottom();
					});
				}, 1000);
			},
			onVolumeChange(e) {
				this.valueWidth = 100 * e.volume + 'px';
				this.voiceRate = e.volume
			},
			playVoice(url){
				console.log(url)
				if (innerAudioContext) {
				  try {
					innerAudioContext.pause();
					innerAudioContext.src = url
					innerAudioContext.play()
				  } catch (e) {
					//TODO handle the exception
				  }
				}
			},
			ontStart() {
				this.voiceText = '';
				console.log('Event: start');
			},
			onRecognizing(e) {
				this.voiceText = e.partialResult;
				console.log('Event: recognizing',e);
			},
			toggleInputMode() {
				this.isVoice = !this.isVoice;
			},
			onRecognition(e) {
				console.log('Event: onRecognition', e);
			},
			onEnd(e) {
				console.log('Event: end', e);
				this.valueWidth = '0px';
				this.voiceRate = 0
			},
			startRecognize() {
				this.recording = true
				let lang = this.speekLangs[this.speekIndex].value
				console.log('startRecognize');
				// #ifdef APP-PLUS
				plus.speech.startRecognize({
					engine: 'baidu',
					lang,
					'userInterface': false,
					'continue': true
				});
				// #endif
			},
			endRecognize() {
				console.log('endRecognize');
				this.recording = false
				// #ifdef APP-PLUS
				plus.speech.stopRecognize();
				// #endif
			}
		}
	}
</script>

<style>
	page {
		height: 100%;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100vh;
		width: 100vw;
		justify-content: center;
		background-color: #F5F5F5;
		padding-bottom: var(--window-bottom);
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.chat-container {
		width: 100%;
		display: flex;
		flex-direction: column;
		flex: 1;
		height: 0;
		box-sizing: border-box;
		background-color: #F5F5F5;
		overflow-y: scroll;
	}

	.message {
		margin: 10rpx 0;
		padding: 20rpx;
		display: flex;
		align-items: flex-start;
		flex-flow: row-reverse;

		&.flexLfet {
			flex-flow: row;

			.message-time {
				text-align: left;
			}

			.avatar {
				margin-right: 10rpx;
			}
		}
	}

	.message-time {
		font-size: 18rpx;
		color: #888;
		margin-bottom: 12rpx;
		text-align: right;

	}

	.message-text {
		padding: 24rpx 32rpx;
		border-radius: 10rpx;
		max-width: 50vw;
		display: inline-block;
		word-wrap: break-word;
		word-break: break-all;
		white-space: pre-wrap;
	}

	.user-message {
		align-self: flex-end;
		background-color: #fff;
		color: rgba(0, 0, 0, 0.8);
	}

	.bot-message {
		align-self: flex-start;
		background-color: #fff;
		color: rgba(0, 0, 0, 0.8);
	}

	.input-area {
		width: 100vw;
		padding: 10rpx;
		box-sizing: border-box;
		background-color: #fff;
		padding-bottom: 32rpx;
		position: relative;
	}

	.voice-text {
		width: 100%;
		padding: 20rpx;
		padding-top: 40rpx;
		max-height: 200rpx;
		box-sizing: border-box;
	}

	.input-box {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		background-color: rgba(0, 0, 0, 0.05);
		border-radius: 40rpx;
		padding: 0 20rpx;

		&.voice-btn {
			text-align: center;
		}
	}

	.send-button {
		padding: 10rpx 20rpx;
		background-color: #007aff;
		color: #fff;
		border: none;
		border-radius: 5rpx;
		cursor: pointer;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		margin-left: 10rpx;
	}

	.voice-icon {
		width: 100rpx;
		padding: 20rpx;
		box-sizing: border-box;
		height: 100rpx;
	}
	.lang_bar {
		height: 100rpx;
		line-height: 100rpx;
		margin: 0 auto;
		border-radius: 100rpx;
		background-color: #ffffff;
		display: flex;
		width: calc(100vw - 128rpx);
		box-sizing: border-box;
		align-items: center;
		padding: 0 48rpx;
	}
	.lang_itm {
		flex: 1;
		width: 0;
		text-align: center;
	}
	.ic-change {
		width: 50rpx;
		height: 50rpx;
	}
</style>